package com.oceansoft.core.common.util;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import com.oceansoft.core.common.constant.ConfigItem;

/**
 * 内核cache，存放架构方面的关键内容。
 * 
 * @author Administrator
 * 
 */
public class CommonUtilCache {

	public static final String KEY_ServletContext = "servletContext";
	public static final String KEY_ApplicationContext = "applicationContext";
	public static final String KEY_WebRealPath = "webRealPath";
	public static final String KEY_ClassRealPath = "classRealPath";
	public static final String KEY_ClassRealURL = "classRealURL";
	public static final String KEY_RootRealPath = "rootRealPath";
	public static final String KEY_UserRealPath = "userRealPath";

	private static Map<String, Object> cache = new ConcurrentHashMap<String, Object>();

	public static void putItem(String oKey, Object instance) {
		cache.put(oKey, instance);
	}

	public static Object getItem(String oKey) {
		return cache.get(oKey);
	}

	/**
	 * 从缓存中取值
	 * 
	 * @param key
	 * @return 值对应的VALUES集合
	 */
	@SuppressWarnings("unchecked")
	public static Set<String> getValues(String key) {
		return (Set<String>) CommonUtilCache.getItem(key);
	}

	/**
	 * 从缓存中获取该KEY对应的VALUE
	 * 
	 * @param key
	 * @return
	 */
	public static String getValue(String key) {
		Object _obj = CommonUtilCache.getItem(key);
		if (null != _obj) {
			ConfigItem item =(ConfigItem)_obj;
			return item.getValue();
//			return _obj.toString();
		} else {
			return null;
		}
	}

	/**
	 * 判断KEY对应的VALUES集合中是否包含需要比对的值
	 * 
	 * @param key
	 * @param compareValue
	 *            需要比对的值
	 * @return 如果存在返回true，否则返回false
	 */
	public static boolean isExistsValue(String key, String compareValue) {
		return getValues(key).contains(compareValue);
	}

	/**
	 * 全局是否包含指定KEY
	 * 
	 * @param key
	 * @return
	 */
	public static boolean isExitsItem(String key) {
		return null != CommonUtilCache.getItem(key);
	}

	/**
	 * 判断系统密钥是否正确(此外配置荐的MUTIL_VALUE项值必须为0,否则无法正确取值)
	 * 
	 * @param appId
	 * @param secretKey
	 * @return
	 */
	public static boolean valueEquals(String appId, String secretKey) {
		Object obj = getItem(String.format("APP_SECRET_%s", appId));
		if (null == obj) {
			return false;
		} else {
			return ((ConfigItem) obj).getValue().equals(secretKey);
		}
	}
}
